import axios from 'axios';
import { transformLang } from '@/utils/tools';
import { i18n, replacePath } from '@/locales';
import { api } from '@/config/api';
import Store from '@/store';
import types from '@/store/types';
import Router from '@/router';

/**
 * API 后端出错时的提示
 *
 * @type {string}
 * @description 出现的情况：
 * 1. 后端非200状态码时的错误，如 404、500、502 等
 * 2. 接口超时，现在为 30000
 */
const API_ERROR_MESSAGE = 'Server Error';

const service = axios.create({
    timeout: 30000,
    headers: {
        post: {
            'Content-Type': 'application/json;charset=UTF-8',
        },
    },
    emulateJSON: true,
    withCredentials: true,
});

service.interceptors.request.use((config) => {
    // Replace link variables, handle request.header
    Object.keys(api).some((key) => {
        if (config.url.indexOf(key) === 0) {
            const target = typeof api[key] === 'string' ? api[key] : api[key].url;
            config.url = config.url.replace(key, target);
            if (typeof api[key].headers === 'function') {
                config.headers = { ...api[key].headers(config), ...config.headers };
            }
            return true;
        }

        return false;
    });

    config.headers = {
        'Accept-Language': transformLang(i18n.global.locale.value),
        ...config.headers,
    };

    // aws上传图片使用put
    if (config.method !== 'put') {
        config.params = {
            r: Math.random().toString(36).substr(2),
            ...config.params,
        };
    }

    return config;
}, error => Promise.reject(error));

/**
 * res数据规范化处理
 *
 * @param {data} res //response data
 * @return {data}
 */
function responseNormalization(res) {
    const data = res.request && res.config ? res.data : res;
    if (typeof data === 'string') {
        return data;
    }
    // data.success = data.success || data.status === 'ok';
    data.code = data.code || data['err-code'] || data.err_code || 200;
    data.message = data.message || data['err-msg'] || data.err_msg || 200;
    return data;
}

service.interceptors.response.use((res) => {
    const data = responseNormalization(res);
    const code = data.code || data.err_code;
    // alert(JSON.stringify(res));
    if (code === 'token-not-valid' || code === 'login-required' || code === 512) {
        // Clear token cookie
        // clearToken();

        // 预渲染时不做处理，因为会导致循环退出
        // 如果当前不是登录页则跳转到登录页
        if (window.location.pathname.indexOf(replacePath('/login')) !== 0) {
            Store.dispatch(types.SET_LOGOUT, { useapi: false }).then(() => {
                Router.push({
                    path: '/login/',
                    query: {
                        backurl: Router.currentRoute.fullPath,
                    },
                });
            });
        }

        // 未登录时返回一个403，没有 message 时 $success $error 不提示
        return {
            code: 403,
        };
        // return Promise.reject(res.data);
    }

    // 解决资产页面切换币种，请求地址时取了上一次的币种
    if (res.config.$parms) {
        data.$parms = res.config.$parms;
    }

    return res.data;
}, error => Promise.reject(error));

/**
 * 重构 service 输出，为了兼容接口异常，导致js崩溃
 */
export default {
    async get(...options) {
        try {
            const res = await service.get(...options);
            return res;
        } catch (e) {
            return Promise.resolve({
                status: 'error',
                code: 500,
                message: API_ERROR_MESSAGE,
                'err-msg': API_ERROR_MESSAGE,
            });
        }
    },
    async post(...options) {
        try {
            const res = await service.post(...options);
            return res;
        } catch (e) {
            return Promise.resolve({
                status: 'error',
                code: 500,
                message: API_ERROR_MESSAGE,
                'err-msg': API_ERROR_MESSAGE,
            });
        }
    },
    async put(...options) {
        try {
            const res = await service.put(...options);
            return res;
        } catch (e) {
            return Promise.resolve({
                status: 'error',
                code: 500,
                message: API_ERROR_MESSAGE,
                'err-msg': API_ERROR_MESSAGE,
            });
        }
    },

    API_ERROR_MESSAGE,
};
